#!/usr/bin/env python3
# coding: utf-8
"""
2025-05-30 检查项目
"""

from PySide6.QtCore import Slot, QSize
from PySide6.QtGui import QAction, QKeySequence,QIntValidator, QTextCursor   
from PySide6.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QHBoxLayout, QPushButton, QWidget,QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, QLabel,QCheckBox,QTextEdit,QGroupBox,QComboBox,QDateTimeEdit,QGridLayout
from PySide6.QtCore import Qt, QModelIndex,QMetaObject,Q_ARG,QDateTime
from PySide6.QtGui import QGuiApplication, QCloseEvent
## from PySide6.QtCore.Qt import 
# from top.wardyan.core.widges.controlls import WTextEdit as QLineEdit

##from PySide6.QtCore import WindowState

## from top.wardyan.core.utils import winformutils
from top.wardyan.core.action.baseaction import WMainWindow,WQdialog
from top.wardyan.core.vo.vos import *
from top.wardyan.core.widges.tables import WTableView

##from warningmain import *
from top.wardyan.core.wdb.core.DBPool import POOL

from top.wardyan.core.vo.vos import *
from top.wardyan.core.wdb.core.db import *
from config import Config
from top.wardyan.core.sqlite import sqliteconfigs

import threading
import time
import re
import sys

from apscheduler.schedulers.background import BackgroundScheduler
from top.wardyan.core.utils.common import *
from top.wardyan.core.wdb.core.dic import *
import uuid


SQL_FIND = "EXEC dbo.yp_check_view @pBeginDate = '1900-01-01', @pEndDate = '2078-12-31 23:59:59', @pText = %s, @pKind = 0, @pType = 0, @pExtID = %d"



        

class ChecktoolCheckEditShell (WQdialog) :
        
    def __init__(self, checkid) -> None:
        ##global cn
        super().__init__("ChecktoolCheckEditShell")
        self.checkid = checkid
        self.table : WTableView = None
        self.main()
        ## self.refreshTable()
        self.load()

    def button_click_add(self) :
        pass


    def handle_double_click(self) :
        pass




    def main(self) :

        HEIGHT = 40
        layout : QVBoxLayout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignVCenter)
        self.setLayout(layout)
        
        

        ## 按钮: 搜索 新增
        topwidget : QWidget = QWidget()
        ##topwidget.setFixedHeight(100)
        layout.addWidget(topwidget)
        topwidget.setFixedHeight(50)
        
        # 设置背景颜色
        #topwidget.setStyleSheet("background-color: #ffff00;padding:0;margin:0;")  # 你可以将 #f0f0f0 替换为你想要的颜色代码

        toplayout : QHBoxLayout = QHBoxLayout()
        toplayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        ##self.setLayout(layout)
        ##layout.addWidget(toplayout)
        topwidget.setLayout(toplayout)
        


        ### 
        btnSave : QPushButton = QPushButton("保存")
        btnSave.setFixedHeight(HEIGHT)
        btnSave.setFixedWidth(150)
        btnSave.clicked.connect(self.save_data)
        btnSave.setDefault(True)
        toplayout.addWidget(btnSave)



        btnAdd : QPushButton = QPushButton("新增")
        btnAdd.setFixedHeight(HEIGHT)
        btnAdd.setFixedWidth(150)
        btnAdd.clicked.connect(self.button_click_add)
        toplayout.addWidget(btnAdd)

        ###################

        ctrlw : QWidget = QWidget()
        ctrllayout : QHBoxLayout = QHBoxLayout()
        ctrlw.setLayout(ctrllayout)
        layout.addWidget(ctrlw)


        ctrllayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        

        ctrlt : QWidget = QWidget()
        tbllayout : QHBoxLayout = QHBoxLayout()
        ctrlt.setLayout(tbllayout)
        layout.addWidget(ctrlt)

        ## sID, xKind, xType, xName, xSQL, xMinVersion, xTableName, xIsStdCheck, xErrorCode, xSQLTemplate, xMaxTimeQty, xUrl, xLevel
        layout = self.layout()  # 获取已有的 QVBoxLayout 主布局

        # 创建一个 QGroupBox 容器来包含表单内容
        form_group_box = QGroupBox("检查项编辑")
        form_layout = QGridLayout()
        form_layout.setColumnStretch(0, 1)  # 标签列比例
        form_layout.setColumnStretch(1, 3)  # 控件列比例

        label_width = 120  # 所有标签统一宽度


        
        self.sIDLineEdit = QLineEdit()
        self.sIDLineEdit.setMaxLength(100)
        self.sIDLineEdit.setReadOnly(True)
        self._add_form_row(form_layout, "ID:", self.sIDLineEdit, label_width)


        # xKind 下拉框
        self.xKindComboBox = QComboBox()
        self.xKindComboBox.setFixedHeight(HEIGHT)
        ## self.xKindComboBox.addItems(["类型A", "类型B", "类型C"])
        # TODO 从数据库字典里读取
        kinds = listDictItem(13000006)
        if kinds is not None :
            for kind in kinds :
                self.xKindComboBox.addItem(kind["xName"], kind["xValue"])
            #self.xKindComboBox.setEditText("不限")
            default_index = self.xKindComboBox.findText("不限")  # 假设你想默认选中 "类型A"
            if default_index >= 0:
                self.xKindComboBox.setCurrentIndex(default_index)
        self._add_form_row(form_layout, "模块:", self.xKindComboBox, label_width)

        # xType 下拉框
        self.xTypeComboBox = QComboBox()
        self.xTypeComboBox.setFixedHeight(HEIGHT)
        #self.xTypeComboBox.addItems(["选项1", "选项2", "选项3"])
        types = listDictItem(13000007)
        if types is not None :
            for type in types :
                self.xTypeComboBox.addItem(type["xName"], type["xValue"])
            #self.xKindComboBox.setEditText("不限")
            default_index = self.xTypeComboBox.findText("每天")  # 假设你想默认选中 "类型A"
            if default_index >= 0:
                self.xTypeComboBox.setCurrentIndex(default_index)

        self._add_form_row(form_layout, "定时周期:", self.xTypeComboBox, label_width)

        # xName 输入框
        self.xNameLineEdit = QLineEdit()
        self.xNameLineEdit.setMaxLength(100)
        self.xNameLineEdit.setFixedHeight(HEIGHT)
        self._add_form_row(form_layout, "名称:", self.xNameLineEdit, label_width)

        # xSQL 多行文本框
        self.xSQLTextEdit = QTextEdit()
        self._add_form_row(form_layout, "检查SQL:", self.xSQLTextEdit, label_width)

        # xMinVersion 日期时间选择
        self.xMinVersionEdit = QDateTimeEdit()
        self.xMinVersionEdit.setDisplayFormat("yyyy-MM-dd")
        #self.xMinVersionEdit.setDateTime(QDateTime.currentDateTime())
        self.xMinVersionEdit.setCalendarPopup(True)  # 启用下拉日历选择
        #self.xMinVersionEdit.setReadOnly(True)
        self.xMinVersionEdit.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.xMinVersionEdit.setFixedWidth(150)
        self.xMinVersionEdit.setFixedHeight(HEIGHT)
        self._add_form_row(form_layout, "最低ERP版本:", self.xMinVersionEdit, label_width)

        # xIsStdCheck 勾选框
        self.xIsStdCheckCheckBox = QCheckBox("标准检查")
        self.xIsStdCheckCheckBox.setFixedHeight(HEIGHT)
        self._add_form_row(form_layout, "标准检查:", self.xIsStdCheckCheckBox, label_width)

        # xTableName 输入框
        self.xTableNameLineEdit = QLineEdit()
        self.xTableNameLineEdit.setFixedHeight(HEIGHT)
        self.xTableNameLineEdit.setMaxLength(100)
        self.xTableNameLineEdit.setPlaceholderText("如果是非标准检查,则可以设置数据表用来保存检查结果")
        self._add_form_row(form_layout, "数据表:", self.xTableNameLineEdit, label_width)

        # xMaxTimeQty 输入框
        self.xMaxTimeQtyLineEdit = QLineEdit()
        self.xMaxTimeQtyLineEdit.setValidator(QIntValidator())  # 限制只能输入整数
        self.xMaxTimeQtyLineEdit.setFixedHeight(HEIGHT)
        self._add_form_row(form_layout, "最长耗时限制:", self.xMaxTimeQtyLineEdit, label_width)

        # xErrorCode 输入框
        self.xErrorCodeLineEdit = QLineEdit()
        self.xErrorCodeLineEdit.setFixedHeight(HEIGHT)
        self._add_form_row(form_layout, "错误代码:", self.xErrorCodeLineEdit, label_width)

        # xLevel 下拉框
        self.xLevelComboBox = QComboBox()
        self.xLevelComboBox.setFixedHeight(HEIGHT)
        #self.xLevelComboBox.addItems(["级别1", "级别2", "级别3"])
        levels = listDictItem(13000025)
        if levels is not None :
            for level in levels :
                self.xLevelComboBox.addItem(level["xName"], level["xValue"])
            default_index = self.xLevelComboBox.findText("无")  # 假设你想默认选中 "类型A"
            if default_index >= 0:
                self.xLevelComboBox.setCurrentIndex(default_index)


        self._add_form_row(form_layout, "错误级别:", self.xLevelComboBox, label_width)

        # xSQLTemplate 多行文本框
        self.xSQLTemplateTextEdit = QTextEdit()
        self._add_form_row(form_layout, "处理模板:", self.xSQLTemplateTextEdit, label_width)

        # xUrl 输入框
        self.xUrlLineEdit = QLineEdit()
        self.xUrlLineEdit.setFixedHeight(HEIGHT)
        self._add_form_row(form_layout, "文档链接:", self.xUrlLineEdit, label_width)

        form_group_box.setLayout(form_layout)
        layout.addWidget(form_group_box)



    def _add_form_row(self, layout: QGridLayout, label_text: str, widget: QWidget, label_width: int):
        row = layout.rowCount()
        label = QLabel(label_text)
        label.setFixedWidth(label_width)
        layout.addWidget(label, row, 0)
        layout.addWidget(widget, row, 1)
    def load(self) :
        datas = query(SQL_FIND, ("", self.checkid))
        if datas is not None and len(datas) > 0 :
            data = datas[0]
            self.load_data(data)
        
    def load_data(self, data: dict):
        """
        加载数据到编辑界面
        :param data: 字典格式的数据，如从数据库查询得到
        """
        self.sIDLineEdit.setText(str(data.get("sID", "")))

        self.xKindComboBox.setCurrentText(data.get("_Kind_Name", ""))
        self.xTypeComboBox.setCurrentText(data.get("_Type_Name", ""))
        self.xNameLineEdit.setText(data.get("xName", ""))
        self.xSQLTextEdit.setPlainText(data.get("xSQL", ""))
        
        # xMinVersion 格式需转换为 QDateTime
        min_version = data.get("xMinVersion")
        if min_version:
            self.xMinVersionEdit.setDateTime(QDateTime.fromString(min_version, "yyyy-MM-dd HH:mm:ss"))
        
        self.xTableNameLineEdit.setText(data.get("xTableName", ""))
        self.xIsStdCheckCheckBox.setChecked(bool(data.get("xIsStdCheck", False)))
        self.xErrorCodeLineEdit.setText(str(data.get("xErrorCode", "")))
        self.xSQLTemplateTextEdit.setPlainText(data.get("xSQLTemplate", ""))
        self.xMaxTimeQtyLineEdit.setText(str(data.get("xMaxTimeQty", "")))
        self.xUrlLineEdit.setText(data.get("xUrl", ""))
        self.xLevelComboBox.setCurrentText(data.get("_Level_Name", "")) 
        
    def generate_update_sql(self, _data_, table_name: str = "yt_check") -> tuple:
        """
        生成 UPDATE SQL 语句和参数列表
        :param _data_: 数据字典，包含 sID 和其他字段
        :param table_name: 要更新的表名
        :return: (sql_query, parameters)
        """
        if not _data_ or 'sID' not in _data_.keys():
            raise ValueError("缺少主键 sID，无法生成更新语句")

        s_id = _data_.pop('sID')  # 取出主键作为 WHERE 条件
        fields = [f"`{k}` = ?" for k in _data_.keys()]
        values = list(_data_.values())
        values.append(s_id)

        sql = f"UPDATE {table_name} SET {', '.join(fields)} WHERE `sID` = ?"
        return sql, values
    def save_data(self) -> dict:
        """
        从界面控件提取数据，返回字典格式
        """
        _data_ = {
            "sID" : self.sIDLineEdit.text().strip(),
            "xKind": self.xKindComboBox.currentData(),
            "xType": self.xTypeComboBox.currentData(),
            "xName": self.xNameLineEdit.text().strip(),
            "xSQL": self.xSQLTextEdit.toPlainText().strip(),
            "xMinVersion": self.xMinVersionEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss"),
            "xTableName": self.xTableNameLineEdit.text().strip(),
            "xIsStdCheck": int(self.xIsStdCheckCheckBox.isChecked()),  # 转为整数 0/1
            "xErrorCode": self.xErrorCodeLineEdit.text().strip(),
            "xSQLTemplate": self.xSQLTemplateTextEdit.toPlainText().strip(),
            "xMaxTimeQty": self.xMaxTimeQtyLineEdit.text().strip(),
            "xUrl": self.xUrlLineEdit.text().strip(),
            # "xLevel": self.xLevelComboBox.currentText()
            "xLevel": self.xLevelComboBox.currentData()
        }
        # print(data)
        #sql, params = self.generate_update_sql(_data_)
        # 执行 SQL（假设你有 execute 函数）
        ## params从list转tuple
        sql = """UPDATE dbo.yt_check 
SET xKind = %d,xType = %d,xName = %s,xSQL = %s,xMinVersion = %s,xTableName = %s,xIsStdCheck = %d,xErrorCode = %d,xSQLTemplate = %s,xMaxTimeQty = %d,xUrl = %s,xLevel = %d
, sVersion = isnull(sVersion, 0) + 1, sLastUpdate = getdate()
WHERE sID= %d
"""
        params = (_data_["xKind"], _data_["xType"], _data_["xName"], _data_["xSQL"], _data_["xMinVersion"], _data_["xTableName"], _data_["xIsStdCheck"], _data_["xErrorCode"], _data_["xSQLTemplate"], _data_["xMaxTimeQty"], _data_["xUrl"], _data_["xLevel"], int(_data_["sID"]))
        exec(sql, tuple(params))
        ## 提示保存OK
        QMessageBox.information(self, "保存成功", "数据保存成功！")
        ## self.load()
        self.close()

    






# if __name__ == "__main__" :     ## or 1 == 1
#     app = QApplication([])
#     w = WWarningEditor()
#     ## w = WScriptWindow()
#     w.show()
#     app.exec()